#include <stdio.h>   /* Standard input/output definitions */
#include <stdlib.h>  /* Standard system clear */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */

#include "captain/capser.h"

int fd;

int initport(int fd) {
	struct termios options;
	// Get the current options for the port...
	tcgetattr(fd, &options);
	// Set the baud rates to 19200...
	cfsetispeed(&options, B9600);
	cfsetospeed(&options, B9600);
	// Enable the receiver and set local mode...
	options.c_cflag |= (CLOCAL | CREAD);

	options.c_cflag &= ~PARENB;
	options.c_cflag &= ~CSTOPB;
	options.c_cflag &= ~CSIZE;
	options.c_cflag |= CS8;

	// Set the new options for the port...
	tcsetattr(fd, TCSANOW, &options);
	return 1;
}

int main(int argc, char **argv) {

char SN;
int opt;
SN='n';
opt=0;
do{
errP:
	system("clear");
	printf("Bienvenido a El Programa De Comunicacion CDC \n");
	printf("1) Abrir Puerto ttyACM0\n");
	printf("2) Abrir Puerto ttyACM1\n");
	printf("3) salir\n");
	scanf("%d",&opt);
	switch(opt)
	{	
	case 1:
		fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NDELAY);
		if (fd == -1) {
			perror("No se pudo abrir el puerto /dev/ttyACM0 - ");
			usleep(1000000);
			goto errP;
		} 
		else {
			fcntl(fd, F_SETFL, 0);
		}
		initport(fd);
		break;
	case 2:
		fd = open("/dev/ttyACM1", O_RDWR | O_NOCTTY | O_NDELAY);
		if (fd == -1) {
			perror("No se pudo abrir el puerto /dev/ttyACM1 - ");
			usleep(1000000);
			goto errP;
		} 
		else {
			fcntl(fd, F_SETFL, 0);
		}
		initport(fd);
		break;
	case 3:
		SN='y';
		close(fd);
	return 0;
	}
	printf("baud=%d\n", getbaud(fd));

	char sCmd[1];
	
int opc2;
opc2=0;
Op2:	
	system("clear");
	printf("El Puerto Se Ha Conectado \n");
	printf("1) Comenzar \n");
	printf("2) Detener \n");
	printf("3) Salir \n");
	
	do{	
		fflush(stdin);
		scanf("%d",&opc2);
		int dk;
		dk=write(fd, "X", 1);
	}while(opc2>=4);
	switch(opc2)
	{
	case 1:	
		sCmd[0] = 0x40;
		int n;
ret:
		n = write(fd, "@", 1);
//		if (!writeport(fd, sCmd)) {
		if(n<0){
			//printf("write failed\n");
			//usleep(20);
			goto ret;
		}
		//printf("written:%s\n", sCmd);
		//usleep(20);
		//fcntl(fd, F_SETFL, FNDELAY);
		goto Op2;
	break;
	case 2:
		sCmd[0] = 0x23;
		int n2;
ret2:
		n2 = write(fd, "#", 1);
/*		if (!writeport(fd, sCmd)) {
			printf("write failed\n");
		}
		printf("written:%s\n", sCmd);
		//usleep(20);
		fcntl(fd, F_SETFL, FNDELAY);
*/
		if(n2<0){
			goto ret2;
		}
		goto Op2;
	break;
	case 3:
		close(fd);
	return 0;
	}

/*	
	char sResult[254];
	fcntl(fd, F_SETFL, FNDELAY); // don't block serial read

	if (!readport(fd,sResult)) {
		printf("read failed\n");
		close(fd);
		return 1;
	}
	printf("readport=%s\n", sResult);
*/
	printf("Desea Continuar?¿ S/N\n");
	scanf("%s",&SN);
}
while (SN!='n');
	close(fd);
	return 0;
}
